/*
 * Copyright By Peak3
 * Copyright By c336bf6ff03a756989bb456b5b5e3271228d43ed38461eb5cb5755d17a2fc9b8
 * All rights reserved.
 *
 * If you are not the intended user, you are hereby notified that any use, disclosure, copying, printing, forwarding or
 * dissemination of this property is strictly prohibited. If you have got this file in error, delete it from your system.
 */

package com.vv.tools.modules.message.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vv.tools.common.util.MessageUtil;
import com.vv.tools.modules.message.converter.MessageConverter;
import com.vv.tools.modules.message.entity.Message;
import com.vv.tools.modules.message.model.MessageDTO;
import com.vv.tools.modules.message.model.request.MessageRequest;
import com.vv.tools.modules.message.service.MessageService;

import jakarta.servlet.http.HttpServletRequest;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;

/**
 * 留言服务实现类
 *
 * @author liwen
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MessageServiceImpl implements MessageService {

    @Override
    public IPage<MessageDTO> getMessagePage(Long current, Long size, Integer status, String keyword) {
        Map<String, Message> all = MessageUtil.getAll();
        IPage<MessageDTO> result = new Page<>();
        if (all.size() < (int) ((current - 1) * size.intValue())) {
            result.setRecords(Collections.emptyList());
        } else {
            List<Message> messages = new ArrayList(all.values()).subList(
                (int) ((current - 1) * size.intValue()),
                (int) Math.min(current * size.intValue(),
                    all.size()));
            result.setRecords(messages.stream().map(MessageConverter.INSTANCE::bo2dto).collect(Collectors.toList()));
        }
        result.setTotal(all.size());
        result.setCurrent(current);
        result.setSize(size);

        // 处理时间显示
        result.getRecords().forEach(this::processTimeDisplay);

        return result;
    }

    @Override
    public IPage<MessageDTO> getPublicMessagePage(Long current, Long size) {
        Map<String, Message> all = MessageUtil.getAll();
        IPage<MessageDTO> result = new Page<>();
        if (all.size() < (int) ((current - 1) * size.intValue())) {
            result.setRecords(Collections.emptyList());
        } else {
            List<Message> messages = new ArrayList(all.values()).subList(
                (int) ((current - 1) * size.intValue()),
                (int) Math.min(current * size.intValue(),
                    all.size()));
            result.setRecords(messages.stream().map(MessageConverter.INSTANCE::bo2dto).collect(Collectors.toList()));
        }
        result.setTotal(all.size());
        result.setCurrent(current);
        result.setSize(size);

        // 处理时间显示
        result.getRecords().forEach(this::processTimeDisplay);

        return result;
    }

    @Override
    public MessageDTO getMessageById(Long id) {
        Message message = MessageUtil.get(String.valueOf(id));
        MessageDTO messageDTO = MessageConverter.INSTANCE.bo2dto(message);
        if (message != null) {
            processTimeDisplay(messageDTO);
        }
        return messageDTO;
    }

    @Override
    public Long submitMessage(MessageRequest request, HttpServletRequest httpRequest) {
        int id = MessageUtil.getAll().size() + 1;
        Message message = new Message();
        message.setNickname(request.getNickname());
        message.setEmail(request.getEmail());
        message.setContent(request.getContent());
        message.setStatus(0);
        message.setIsTop(0);
        message.setLikeCount(0);
        message.setId(Long.parseLong(id + ""));

        // 获取IP地址和User-Agent
        message.setIpAddress(getClientIpAddress(httpRequest));
        message.setUserAgent(httpRequest.getHeader("User-Agent"));

        MessageUtil.put(String.valueOf(id), message);
        return Long.parseLong(id + "");
    }

    @Override
    public Boolean auditMessage(Long id, Integer status, String reply) {
        return false;
    }

    @Override
    public Boolean deleteMessage(Long id) {
        Message message = MessageUtil.get(String.valueOf(id));
        if (message == null) {
            return false;
        }

        message.setIsDeleted("Y");
        MessageUtil.put(String.valueOf(id), message);
        return true;
    }

    @Override
    public Boolean topMessage(Long id, Integer isTop) {
        Message message = MessageUtil.get(String.valueOf(id));
        if (message == null) {
            return false;
        }

        message.setIsTop(isTop);
        MessageUtil.put(String.valueOf(id), message);
        return true;
    }

    @Override
    public Integer likeMessage(Long id) {
        Message message = MessageUtil.get(String.valueOf(id));
        if (message == null) {
            return 0;
        }

        Integer currentLikes = message.getLikeCount() == null ? 0 : message.getLikeCount();
        message.setLikeCount(currentLikes + 1);
        MessageUtil.put(String.valueOf(id), message);

        return message.getLikeCount();
    }

    @Override
    public Map<String, Object> getMessageStats() {
        Map<String, Object> result = new HashMap<>();

        // 初始化统计数据
        result.put("total", 0);
        result.put("pending", 0);
        result.put("approved", 0);
        result.put("rejected", 0);

        // 计算总数
        Long total = (Long) result.get("pending") + (Long) result.get("approved") + (Long) result.get("rejected");
        result.put("total", total);

        return result;
    }

    @Override
    public Boolean batchDeleteMessages(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }

        return false;
    }

    /**
     * 处理时间显示
     */
    private void processTimeDisplay(MessageDTO messageDTO) {
        if (messageDTO.getGmtCreated() != null) {
            messageDTO.setCreateTimeDisplay(formatFriendlyTime(messageDTO.getGmtCreated()));
        }

        // 设置状态描述
        if (messageDTO.getStatus() != null) {
            switch (messageDTO.getStatus()) {
                case 0:
                    messageDTO.setStatusDesc("待审核");
                    break;
                case 1:
                    messageDTO.setStatusDesc("已通过");
                    break;
                case 2:
                    messageDTO.setStatusDesc("已拒绝");
                    break;
                default:
                    messageDTO.setStatusDesc("未知");
            }
        }
    }

    /**
     * 格式化友好时间显示
     */
    private String formatFriendlyTime(LocalDateTime dateTime) {
        LocalDateTime now = LocalDateTime.now();
        long minutes = ChronoUnit.MINUTES.between(dateTime, now);
        long hours = ChronoUnit.HOURS.between(dateTime, now);
        long days = ChronoUnit.DAYS.between(dateTime, now);

        if (minutes < 1) {
            return "刚刚";
        } else if (minutes < 60) {
            return minutes + "分钟前";
        } else if (hours < 24) {
            return hours + "小时前";
        } else if (days < 7) {
            return days + "天前";
        } else {
            return dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }

        // 如果有多个IP，取第一个
        if (ipAddress != null && ipAddress.contains(",")) {
            ipAddress = ipAddress.split(",")[0].trim();
        }

        return ipAddress;
    }
}
